package com.example.teachmvandroidchart.ui

import android.animation.ValueAnimator
import android.graphics.Color
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.text.format.DateFormat
import android.util.Log
import android.view.animation.LinearInterpolator
import com.android.frame.mvp.CommonBaseActivity
import com.android.util.threadPool.ThreadPoolManager
import com.example.teachmvandroidchart.R
import com.example.teachmvandroidchart.databinding.ActivityMainBinding
import com.example.teachmvandroidchart.mqtt.CreatClinent
import com.example.teachmvandroidchart.util.*
import com.example.teachmvandroidchart.util.Constant.Companion.RECEIVE_DATA
import com.example.teachmvandroidchart.util.Constant.Companion.RECEIVE_FLAG

import com.example.teachmvandroidchart.util.State.waterTime
import com.example.teachmvandroidchart.widget.DynamicLineChartManager
import com.example.teachmvandroidchart.widget.LoadingDialog.LoadingDialog
import com.gyf.immersionbar.ImmersionBar
import okhttp3.*
import java.util.concurrent.TimeUnit
import org.json.JSONObject

import org.json.JSONException
import java.io.*
import java.net.URI
import java.util.ArrayList


/**
 * Created by dell on 2021/8/11.mvp
 */
class MainActivity: CommonBaseActivity<ActivityMainBinding>() {
    private var okHttpClient: OkHttpClient? = null
    private var okHttp: OkHttpClient? = null
    private var dynamicLineChartManager2: DynamicLineChartManager? = null
    private var clinent = CreatClinent(this) // 实例化MQTT连接
    private var t_flag = false // 线程循环标志 - 消息面板

    private var ip = ""  //默认ip
    private var port = ""  //默认端口号
    private var driverid = ""
    private var productid = ""
    private var password = ""
    private var flag = false // 是否在线
    private var Water_Switch = "1" // 是否在线

    private val list: MutableList<Float> = ArrayList() //数据集合
    private val names: MutableList<String> = ArrayList() //折线名字集合
    private val colour: MutableList<Int> = ArrayList() //折线颜色集合
    override fun handleView(savedInstanceState: Bundle?) {
        intView()
        initData()
    }

    private fun intView() {
        //折线名字
        names.add("湿度")
        names.add("温度")
        //折线颜色
        colour.add(Color.CYAN)
        colour.add(Color.GREEN)
        //实现多条曲线
        dynamicLineChartManager2 = DynamicLineChartManager(binding.chartTmp, names, colour)
        dynamicLineChartManager2!!.setYAxis(100f, 0f, 8)
        dynamicLineChartManager2!!.setDescription("diagram")
        ImmersionBar.with(this).titleBar(binding.toolbar).init()
        ImmersionBar.with(this).titleBar(binding.toolbar).keyboardEnable(true).init()
        setSupportActionBar(binding.toolbar)
        val actionBar = supportActionBar
        actionBar?.setDisplayHomeAsUpEnabled(true)
    }



    private fun parseEasyJson(json: String) {
        try {
            val root = JSONObject(json)
            Water_Switch = root.getString("Water_Switch")

            val temp = root.getString("Temp")
            val hume = root.getString("humi")
            val sysTime = System.currentTimeMillis() //获取系统时间
            val sysTimeStr: CharSequence = DateFormat.format("yyyy-MM-dd HH:mm:ss", sysTime) //时间显示格式


            Handler(Looper.getMainLooper()).postDelayed({
                binding.temp.text = temp
                binding.hume.text = hume
                binding.updatetime.text = sysTimeStr
                //添加多条曲线的数据
                list.add(hume.toFloat())
                list.add(temp.toFloat())
                dynamicLineChartManager2!!.addEntry(list)
                list.clear()
            }, 300)
        } catch (e: JSONException) {
            e.printStackTrace()
        }
    }

    override fun initListener() {
        //设置设备连接端
        binding.Set.setOnClickListener {
//            clinent.disconnect() //断开连接
            startActivity(SettingActivity ::class.java)
        }
        //t浇水
        binding.progressBtn.setOnClickListener {
            ThreadPoolManager.instance.getFixedThreadPool().shutdownNow()
            ThreadPoolManager.instance.getScheduledThreadPool().shutdownNow()
            binding.loadingLayout.loadStart()
            ThreadPoolManager.instance.getScheduledThreadPool().schedule(Runnable {
                binding.loadingLayout.loadComplete()
            },2, TimeUnit.SECONDS)
            //修改状态
            ThreadPoolManager.instance.getScheduledThreadPool().schedule(Runnable {
                clinent.sendMqtt(Constant.SUBSCRIBE,"Water:1")
            }, 0, TimeUnit.SECONDS)
            ThreadPoolManager.instance.getScheduledThreadPool().schedule(Runnable {
                clinent.sendMqtt(Constant.SUBSCRIBE,"Water:0")
            }, State.waterTime.toLong(), TimeUnit.SECONDS)
            val animator = ValueAnimator.ofInt(0, 100)
            animator.addUpdateListener {
                //onAnimationUpdate的调用次数和setDuration有关
                val value = it.animatedValue  //数值
                val fraction = it.animatedFraction  //百分比
                binding.progressPb.progress = value as Int
            }
            animator.interpolator = LinearInterpolator()
            animator.setDuration(waterTime *1000.toLong()).start()
        }
        //设置时间
        binding.setTime.setOnClickListener {
            Handler(Looper.getMainLooper()).postDelayed({
                //保存和读取
                SPTool.getInstance(this) !!.putInt("WaterTime", binding.waterTime.text.toString().toInt())
                State.waterTime = SPTool.getInstance(this) !!
                    .getInt("WaterTime",5).toInt()
                ToastUtil.showToast("时间更改成功\n"+State.waterTime+"秒")
                binding.waterTime.clearFocus();	//清除焦点
            }, 100)
        }
        //控制开关字体颜色

        binding.SwitchWater.setOnCheckedChangeListener { _, b ->
            if (b) {
                clinent.sendMqtt(Constant.SUBSCRIBE,"Water:1")
                binding.loadingLayout.loadStart()
                ThreadPoolManager.instance.getScheduledThreadPool().schedule(Runnable {
                    binding.loadingLayout.loadComplete()
                },2, TimeUnit.SECONDS)

            } else {
                binding.loadingLayout.loadStart()
                ThreadPoolManager.instance.getScheduledThreadPool().schedule(Runnable {
                    binding.loadingLayout.loadComplete()
                },2, TimeUnit.SECONDS)
                clinent.sendMqtt(Constant.SUBSCRIBE,"Water:0")
            }
        }
        val apkDownloadUtil = ApkDownloadUtil(this)
        //跟新软件
        binding.update.setOnClickListener {

            apkDownloadUtil.downLoadApk("http://app.mail.qq.com/cgi-bin/mailapp?latest=y&from=2")
        }
        //刷新
        binding.refresh.setOnClickListener {
            Getonline()
            ToastUtil.showToast("刷新成功")
        }
        //toolbar返回按钮监听
        binding.toolbar.setNavigationOnClickListener { finish() }
    }

    private fun initData() {
        Handler(Looper.getMainLooper()).postDelayed({
            /**
             * 数据初始化（200毫秒）
             * */
            State.ip = SPTool.getInstance(this) !!
                .getString("ip", "").toString()
            State.DriveID = SPTool.getInstance(this) !!
                .getString("DriveID", "").toString()
            State.ProductID = SPTool.getInstance(this) !!
                .getString("ProductID", "").toString()
            State.zhuti = SPTool.getInstance(this) !!
                .getString("zhuti", "").toString()
            State.port = SPTool.getInstance(this) !!
                .getString("port", "").toString()
            State.password = SPTool.getInstance(this) !!
                .getString("password", "").toString()
            State.waterTime = SPTool.getInstance(this) !!
                .getInt("WaterTime",5).toInt()
            Connet()
            Getonline()
            getAsync()

        }, 500)
        ThreadPoolManager.instance.getScheduledThreadPool().schedule(Runnable {
            Subject()

        }, 1, TimeUnit.SECONDS)

    }
    //订阅
    private fun Subject() {
        if (Constant.CONNECT_FLAG) { //如果建立连接
            Constant.SUBSCRIBE = State.zhuti
            SPTool.getInstance(this) !!.putString("zhuti", Constant.SUBSCRIBE)
            if (!Constant.SUBSCRIBE_FLAG) {
                clinent.subscribe(Constant.SUBSCRIBE)
                if (Constant.SUBSCRIBE_FLAG) {
                    t_flag = true //循环线程
                    //开启线程 对接收消息处理并更新消息view  只有在订阅主题后才能接收到来自主题的消息，所以放在此处
                    myThread()
                    ToastUtil.showToast("订阅成功")
                }
            } else {
                t_flag = false //退出循环线程
                clinent.unsubscribe(Constant.SUBSCRIBE) //退订主题
                ToastUtil.showToast("退订成功")
            }
        } else {
            ToastUtil.showToast("请先建立连接")
        }
    }
    // 连接
    private fun Connet() {
        var f_kq = false
        if (!Constant.CONNECT_FLAG) { //没有连接，建立连接
            driverid = State.DriveID
            productid = State.ProductID
            password = State.password
            if (driverid.isNotEmpty()) { //如果id不为空
                ip = State.ip
                port = State.port
                if (productid.isNotEmpty()) //如果用户名不为空
                    clinent.mqttClient(ip, port, driverid, productid, password)
                else {//为空则传入
                    clinent.mqttClient(ip, port, driverid)
                }
                f_kq = true
                //线程更新UI
                val thread = Thread(Runnable {
                    while (f_kq) {
                        if (Constant.CONNECT_FLAG) {//MQTT连接
                            val mMessage = Message.obtain()
                            mMessage.what = 1
                            f_kq = false
                        } else {
                            val mMessage = Message.obtain()
                            mMessage.what = 2
                        }
                        Thread.sleep(300)
                    }
                })
                thread.start()
            } else {
                ToastUtil.showToast("连接DriveID为空")
            }
        } else { // 已经连接，断开连接
            clinent.disconnect() //断开连接
            if (!Constant.CONNECT_FLAG) { //判断现在连接状态，如果处于断开连接状态
                ToastUtil.showToast("断开连接")
                Constant.SUBSCRIBE_FLAG = false  // 订阅主题标志
                Constant.SUBSCRIBE = ""  //清空订阅主题内容
            } else {
                ToastUtil.showToast("断开连接失败")
            }
        }
    }

    /**
     * 获取网络数据
     */
    private fun getAsync() {
        okHttpClient = OkHttpClient()
        val request = Request.Builder()
            .url(
                "https://devapi.qweather.com/v7/weather/now?" +"location=" +State.CityID+"&"+"key="+State.KEY

            )
            .build()
        val call = okHttpClient !!.newCall(request)
        call.enqueue(object : Callback {
            @Throws(IOException::class)
            override fun onResponse(call: Call, response: Response) {
                try {
                    /*response.body().string()中的 (.string)只能使用一次*/
                    val responseData = response.body() !!.string()
                    val root = JSONObject(responseData)
                    val weather = root.getJSONObject("now")
                    val temp = weather.getString("temp")
                    val hume = weather.getString("humidity")
                    val windDir = weather.getString("windDir")
                    val windScale = weather.getString("windScale")
                    val text = weather.getString("text")
                    Handler(Looper.getMainLooper()).postDelayed({
                        binding.tianqi.text = text
                        binding.fengli.text = windDir+"  "+windScale+"级"
                        binding.wendu.text = temp+" ℃"
                        binding.shidu.text = hume+" %RH"
                        binding.waterTime.setText( State.waterTime.toString())
                    }, 300)
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }

            override fun onFailure(call: Call, e: IOException) {}
        })
    }
    /**
     * 获取网络数据--
     */

    private fun Getonline() {
        okHttp = OkHttpClient()
        val request = Request.Builder()
            .url(
                "https://api.heclouds.com/devices/" +State.Drive2ID
            )
            .addHeader(
                "api-key",State.api_key
            )
            .build()
        val call = okHttp !!.newCall(request)
        call.enqueue(object : Callback {
            @Throws(IOException::class)
            override fun onResponse(call: Call, response: Response) {
                try {
                    /*response.body().string()中的 (.string)只能使用一次*/

                    val responseData = response.body() !!.string()
                    Log.e("MQTT",responseData)
                    val root = JSONObject(responseData)
                    val data = root.getJSONObject("data")
                    flag = data.getBoolean("online")
                    val create_time = data.getString("create_time")
                    val last_ct = data.getString("last_ct")
                    Handler(Looper.getMainLooper()).postDelayed({
                        if(flag){
                            binding.online.text = "🍀"
                            binding.temp.text = "等待..."
                            binding.hume.text = "等待...";
                            binding.createTime.text = create_time;
                            binding.updatetime.text = "须等待10-50秒\n不影响功能的使用";
                        }else{
                            binding.online.text = "🔴";binding.temp.text = "设备不在线"
                            binding.hume.text = "设备不在线";
                            binding.updatetime.text = "最后在线时间\n"+last_ct;
                            binding.createTime.text = create_time;
                        }

                    }, 300)
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }

            override fun onFailure(call: Call, e: IOException) {}
        })
    }
    //线程
    fun myThread() {
        var thread = Thread(Runnable {
            while (t_flag) {
                if (RECEIVE_FLAG) {  //如果接到消息
                    parseEasyJson(RECEIVE_DATA)
                    RECEIVE_FLAG = false //将消息标志位置位
                    ThreadPoolManager.instance.getScheduledThreadPool().schedule(Runnable {
                        if(Water_Switch=="0"){
                            //修改图片等
                            binding.progressBtn.setImageResource(R.drawable.ic_switch_off)
                            binding.loadingLayout.loadComplete()
                        }else{
                            binding.progressBtn.setImageResource(R.drawable.ic_switch_on)
                            binding.loadingLayout.loadComplete()
                        }
                    }, 0, TimeUnit.SECONDS)



                    Thread.sleep(500)
                }
            }
        })
        thread.start()
    }
    //线程
//    fun myThread() {
//        ThreadPoolManager.instance.getScheduledThreadPool().scheduleWithFixedDelay(Runnable {
//            if (RECEIVE_FLAG) {  //如果接到消息
//                Json(RECEIVE_DATA)
//                parseEasyJson(RECEIVE_DATA)
//                RECEIVE_FLAG = false //将消息标志位置位
//                if(Water_Switch=="0"){
//                    binding.progressBtn.setImageResource(R.mipmap.ic_irrigate_yes)
//                    ToastUtil.showToast("发送成功")
//                }else
//                    binding.progressBtn.setImageResource(R.mipmap.ic_irrigate_no);
//                ToastUtil.showToast("发送失败");
//                Thread.sleep(300)
//            }
//        }, 0, 1, TimeUnit.SECONDS)
//    }

}
